package com.bookstore.back.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bookstore.back.common.Result;
import com.bookstore.back.entity.Order;
import com.bookstore.back.entity.OrderItem;
import com.bookstore.back.entity.User;
import com.bookstore.back.service.OrderItemService;
import com.bookstore.back.service.OrderService;
import com.bookstore.back.util.UserContextUtil;
import com.bookstore.back.vo.OrderVO;
import com.bookstore.back.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 订单控制器
 *
 * @author 程序猿_Ti
 * @since 2025-07-24
 */
@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private UserContextUtil userContextUtil;

    /**
     * 获取当前用户的订单列表
     */
    @GetMapping
    public Result getUserOrders(@RequestParam(defaultValue = "1") Integer current,
                               @RequestParam(defaultValue = "10") Integer size,
                               @RequestParam(required = false) Integer status) {
        UserVO user = userContextUtil.getCurrentUser();
        if (user == null) {
            return Result.error("用户未登录");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("current", current);
        params.put("size", size);
        params.put("userId", user.getId().toString());

        if (status != null) {
            params.put("status", status.toString());
        }

        IPage<Order> page = orderService.getOrderList(params);
        Map<String, Object> data = new HashMap<>();
        data.put("page", page);
        return Result.success(data);
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{id}")
    public Result getOrderDetail(@PathVariable("id") Integer id) {
        UserVO user = userContextUtil.getCurrentUser();
        if (user == null) {
            return Result.error("用户未登录");
        }

        Map<String, Object> orderDetail = orderService.getOrderDetailWithInfo(id);
        if (orderDetail == null) {
            return Result.error("订单不存在");
        }

        OrderVO orderVO = (OrderVO) orderDetail.get("order");
        // 验证是否是当前用户的订单（普通用户只能查看自己的订单）
        if (!user.getUserType().equals("admin") && !user.getUserType().equals("merchant") && !orderVO.getUserId().equals(user.getId().intValue())) {
            return Result.error("无权访问该订单");
        }

        Map<String, Object> data = new HashMap<>();
        data.put("data", orderDetail);
        return Result.success(data);
    }

    /**
     * 创建订单
     */
    @PostMapping
    public Result createOrder(@RequestBody Map<String, Object> orderData) {
        UserVO user = userContextUtil.getCurrentUser();
        if (user == null) {
            return Result.error("用户未登录");
        }

        try {
            // 创建订单
            Order order = new Order();
            order.setUserId(user.getId().intValue());
            order.setOrderNo(generateOrderNumber());

            order.setStatus(0); // 待支付

            // 设置订单金额
            BigDecimal totalAmount = new BigDecimal(orderData.get("totalAmount").toString());
            BigDecimal actualAmount = new BigDecimal(orderData.get("actualAmount").toString());
            BigDecimal discountAmount = orderData.get("discountAmount") != null ?
                new BigDecimal(orderData.get("discountAmount").toString()) : BigDecimal.ZERO;
            BigDecimal shippingFee = orderData.get("shippingFee") != null ?
                new BigDecimal(orderData.get("shippingFee").toString()) : BigDecimal.ZERO;

            order.setTotalAmount(totalAmount);
            order.setActualAmount(actualAmount);
            order.setDiscountAmount(discountAmount);
            order.setShippingFee(shippingFee);

            // 设置收货信息
            Map<String, Object> addressInfo = (Map<String, Object>) orderData.get("address");
            if (addressInfo != null) {
                order.setAddressId(Integer.parseInt(addressInfo.get("id").toString()));
                order.setReceiverName(addressInfo.get("receiverName").toString());
                order.setReceiverPhone(addressInfo.get("receiverPhone").toString());
                order.setReceiverAddress(addressInfo.get("fullAddress").toString());
            }

            // 设置备注
            if (orderData.get("remark") != null) {
                order.setRemark(orderData.get("remark").toString());
            }

            // 保存订单
            orderService.save(order);

            // 保存订单项
            List<Map<String, Object>> items = (List<Map<String, Object>>) orderData.get("items");
            for (Map<String, Object> item : items) {
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(order.getId());
                orderItem.setBookId(Integer.parseInt(item.get("bookId").toString()));
                orderItem.setBookTitle(item.get("title").toString());
                orderItem.setBookCover(item.get("cover").toString());
                orderItem.setPrice(new BigDecimal(item.get("price").toString()));
                orderItem.setQuantity(Integer.parseInt(item.get("quantity").toString()));
                orderItem.setSubtotal(orderItem.getPrice().multiply(new BigDecimal(orderItem.getQuantity())));

                orderItemService.save(orderItem);
            }

            Map<String, Object> data = new HashMap<>();
            data.put("orderId", order.getId());
            data.put("orderNo", order.getOrderNo());
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建订单失败：" + e.getMessage());
        }
    }

    /**
     * 支付订单
     */
    @PostMapping("/{id}/pay")
    public Result payOrder(@PathVariable("id") Integer id, @RequestBody Map<String, Object> payData) {
        UserVO user = userContextUtil.getCurrentUser();
        if (user == null) {
            return Result.error("用户未登录");
        }

        Order order = orderService.getById(id);
        if (order == null) {
            return Result.error("订单不存在");
        }

        // 验证是否是当前用户的订单
        if (!order.getUserId().equals(user.getId().intValue())) {
            return Result.error("无权操作该订单");
        }

        // 验证订单状态
        if (order.getStatus() != 0) {
            return Result.error("订单状态不正确，无法支付");
        }

        // 设置支付方式
        Integer paymentType = Integer.parseInt(payData.get("paymentType").toString());
        order.setPaymentType(paymentType);

        // 更新订单状态为已支付
        order.setStatus(1);
        order.setPaymentTime(LocalDateTime.now());
        
        // 直接更新整个订单对象，确保支付方式被保存
        boolean success = orderService.updateById(order);
        if (success) {
            return Result.success("支付成功");
        } else {
            return Result.error("支付失败");
        }
    }

    /**
     * 确认收货
     */
    @PostMapping("/{id}/confirm")
    public Result confirmOrder(@PathVariable("id") Integer id) {
        UserVO user = userContextUtil.getCurrentUser();
        if (user == null) {
            return Result.error("用户未登录");
        }

        Order order = orderService.getById(id);
        if (order == null) {
            return Result.error("订单不存在");
        }

        // 验证是否是当前用户的订单
        if (!order.getUserId().equals(user.getId().intValue())) {
            return Result.error("无权操作该订单");
        }

        // 验证订单状态
        if (order.getStatus() != 2) {
            return Result.error("订单状态不正确，无法确认收货");
        }

        // 更新订单状态为已完成
        boolean success = orderService.updateOrderStatus(id, 3);
        if (success) {
            return Result.success("确认收货成功");
        } else {
            return Result.error("确认收货失败");
        }
    }

    /**
     * 取消订单
     */
    @PostMapping("/{id}/cancel")
    public Result cancelOrder(@PathVariable("id") Integer id, @RequestBody Map<String, Object> cancelData) {
        UserVO user = userContextUtil.getCurrentUser();
        if (user == null) {
            return Result.error("用户未登录");
        }

        Order order = orderService.getById(id);
        if (order == null) {
            return Result.error("订单不存在");
        }

        // 验证是否是当前用户的订单
        if (!order.getUserId().equals(user.getId().intValue())) {
            return Result.error("无权操作该订单");
        }

        // 验证订单状态，只有待支付的订单可以取消
        if (order.getStatus() != 0) {
            return Result.error("订单状态不正确，无法取消");
        }

        String reason = cancelData.get("reason") != null ? cancelData.get("reason").toString() : "用户取消";
        boolean success = orderService.cancelOrder(id, reason);
        if (success) {
            return Result.success("取消订单成功");
        } else {
            return Result.error("取消订单失败");
        }
    }

    /**
     * 获取订单统计数据
     */
    @GetMapping("/stats")
    public Result getOrderStats() {
        UserVO user = userContextUtil.getCurrentUser();
        if (user == null) {
            return Result.error("用户未登录");
        }

        // 获取当前用户各状态的订单数量
        Map<String, Object> params = new HashMap<>();
        params.put("userId", user.getId().toString());

        Map<String, Object> stats = new HashMap<>();

        // 待支付订单
        params.put("status", "0");
        IPage<Order> pendingPage = orderService.getOrderList(params);
        stats.put("pending", pendingPage.getTotal());

        // 待发货订单
        params.put("status", "1");
        IPage<Order> paidPage = orderService.getOrderList(params);
        stats.put("paid", paidPage.getTotal());

        // 待收货订单
        params.put("status", "2");
        IPage<Order> shippedPage = orderService.getOrderList(params);
        stats.put("shipped", shippedPage.getTotal());

        // 已完成订单
        params.put("status", "3");
        IPage<Order> completedPage = orderService.getOrderList(params);
        stats.put("completed", completedPage.getTotal());

        // 已取消订单
        params.put("status", "4");
        IPage<Order> cancelledPage = orderService.getOrderList(params);
        stats.put("cancelled", cancelledPage.getTotal());

        // 所有订单
        params.remove("status");
        IPage<Order> allPage = orderService.getOrderList(params);
        stats.put("all", allPage.getTotal());

        Map<String, Object> data = new HashMap<>();
        data.put("data", stats);
        return Result.success(data);
    }

    /**
     * 生成订单号
     */
    private String generateOrderNumber() {
        // 生成格式：BK + 年月日 + 6位随机数
        LocalDateTime now = LocalDateTime.now();
        String dateStr = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String randomStr = UUID.randomUUID().toString().substring(0, 6);
        return "BK" + dateStr + randomStr;
    }
}
